package com.lv.service.workmanager

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lv.common.utils.Constants
import com.lv.service.bean.ReceiptAddressBean
import com.lv.service.room.address.LocationNewReceiptAddressDbHelper
import com.lv.service.room.address.ReceiptAddressItem
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException

/**
 * 作者： ygx
 * 创建日期：2023/4/19 7:37 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class LoadInfoWorker(private val context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

    private val mBeans = mutableListOf<ReceiptAddressItem>()

    override fun doWork(): Result {
        val string = inputData.getString("name") ?: "-1"
        getAddressData(string)
        LogUtils.e("打印线程：${Thread.currentThread().name}===$string")
        return Result.success()
    }

    private fun getAddressData(isRefresh: String) {
        val client = OkHttpClient()
        //创建请求连接，url里面存放请求连接，get表示其实get请求
        val request: Request = Request.Builder().url(Constants.ADDRESS_NET_NEWRECEIPT).get().build()
        try {
            //使用execute()方法执行请求
            val response = client.newCall(request).execute()
            //定义字符串接收请求信息
            val result = response.body?.string()
            saveAddressData(result, isRefresh)
        } catch (e: IOException) {
            e.printStackTrace()
        }
//        val ktRetrofit = KtRetrofit.initConfig(getBaseHost())
//        ktRetrofit.getService(AddressService::class.java)
//            .getAllAddressInfo()
//            .enqueue(object : retrofit2.Callback<ResponseBody> {
//                override fun onResponse(
//                    call: Call<ResponseBody>,
//                    response: Response<ResponseBody>
//                ) {
//                    val result = response.body()?.string()
//                    saveAddressData(result)
//                }
//
//                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//                    t.printStackTrace()
//
////                    val json = getj("city.json")
//                    val stringBuilder = StringBuilder()
//                    try {
//                        val assetManager: AssetManager = context.assets
//                        val bf = BufferedReader(
//                            InputStreamReader(
//                                assetManager.open("city.json")
//                            )
//                        )
//                        var line: String?
//                        while (bf.readLine().also { line = it } != null) {
//                            stringBuilder.append(line)
//                        }
//                    } catch (e: IOException) {
//                        e.printStackTrace()
//                    }
//                    val json = stringBuilder.toString()
//
////                    saveAddressData(json)
//                }
//
//            })

//        fun getJson(fileName: String?): String? {
//            val stringBuilder = StringBuilder()
//            try {
//                val assetManager: AssetManager = YgxApplication.getInstance().assets
//                val bf = BufferedReader(
//                    InputStreamReader(
//                        assetManager.open(fileName!!)
//                    )
//                )
//                var line: String?
//                while (bf.readLine().also { line = it } != null) {
//                    stringBuilder.append(line)
//                }
//            } catch (e: IOException) {
//                e.printStackTrace()
//            }
//            return stringBuilder.toString()
//        }
    }

    private fun saveAddressData(result: String?, isRefresh: String) {
        val listType = object : TypeToken<ReceiptAddressBean>() {}.type
        val datas: ReceiptAddressBean = Gson().fromJson(result, listType)
        datas.let {
            val code = SPStaticUtils.getString(Constants.ADDRESS_NET_CODE, "-100")
            if (datas.code != code || isRefresh != "-1") {
                SPStaticUtils.put(Constants.ADDRESS_NET_CODE, datas.code)
//                LocationNewReceiptAddressDbHelper.deleteAllLocation(context)
                val newreceiptAddress = datas.data.newreceiptAddress
                if (newreceiptAddress != null) {
                    mBeans.clear()
                    mBeans.addAll(newreceiptAddress)

                    GlobalScope.launch {
                        val addressBeans = mutableListOf<ReceiptAddressItem>()
                        for ((index, e) in mBeans.withIndex()) {
                            val addressBean = ReceiptAddressItem(
                                index,
                                e.id,
                                e.name,
                                e.firstChar,
                                e.forshort,
                                e.pforshort,
                                e.seq,e.centre,
                                e.isShow,
                                e.telSecondCategories,
                            )
                            addressBeans.add(addressBean)
                        }
                        LocationNewReceiptAddressDbHelper.insertAllLocation(
                            context,
                            addressBeans
                        )
                    }

                }
            }
        }

    }
}